package com.inboyu.admin.domain;

import java.util.List;

/**
 * 管理域领域服务类
 */
public class ContractDomainService {

    private final ContractRepository contractRepository;

    private final OperationLogRepository operationLogRepository;

    private final ResourceRepository resourceRepository;

    public ContractDomainService(final ContractRepository contractRepository,
                                 final OperationLogRepository operationLogRepository,
                                 final ResourceRepository resourceRepository)
    {
        this.contractRepository = contractRepository;
        this.operationLogRepository = operationLogRepository;
        this.resourceRepository = resourceRepository;
    }

    /**
     * 查询操作日志
     * @param storeId
     * @param operator
     * @param operationTimeStart
     * @param operationTimeEnd
     * @return
     */
    public List<OperationLogEntity> findOperationLogByCondition(String storeId, String operator,
                                                                String operationTimeStart, String operationTimeEnd) {
        return operationLogRepository.findByCondition(storeId, operator, operationTimeStart, operationTimeEnd);
    }

    public ContractEntity findContractByStoreId(String storeId) {
        return contractRepository.findByStoreId(storeId);
    }

    /**
     * 保存资源
     * @param resource
     * @return
     */
    public int saveResource(ResourceEntity resource) {
        return resourceRepository.save(resource);
    }

    /**
     * 保存合同
     * @param contract
     * @return
     */
    public int saveContract(ContractEntity contract) {
        // 1、通过门店ID获取对应库中最新的合同信息
        ContractEntity contractEntityOld = findContractByStoreId(contract.getStoreId().toString());
        // 2、历史合同更新字段比对和对应版本逻辑加1处理
        contract.createContract("当前登录用户", contractEntityOld.getVersion());
        // 3、todo 写入操作记录
        operationLogRepository.save(OperationLogEntity.init(contractEntityOld, contract));
        // 4、更新旧合同
        contractEntityOld.deleteContract("当前登录用户");
        contractRepository.update(contractEntityOld);
        // 5、保存新合同
        return contractRepository.save(contract);
    }
}
